<?php

namespace App\Models;

use App\Util\Tool;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class AddressBookLabel extends Model
{
    protected $table = 'c_address_book_labels';

    protected $fillable = ['label_name', 'doctor_id', 'work_id','is_default','lab_type','num'];


    /**
     * @param $filter
     * 通讯录添加label
     */
    public function addAddressBookLabel($filter)
    {
        if (isset($filter['id'])) {
            $info = $this->where([['id', '=', $filter['id']]])->first();
            $info->label_name = isset($filter['label_name']) ? $filter['label_name'] : $info->label_name;
            $res = $info->save();
        } else {
            $res = $this->create($filter);
        }
        if ($res) {
            return true;
        }
        return "添加失败";
    }

    /**
     * @param $filter
     * @return bool|string
     * 删除用户标签
     */
    public function delUserAddressBookLabel($filter)
    {
        $info = (new AddressBookRelateLabel())->where([['address_book_id', '=', $filter['address_book_id']], ['address_book_label_id', '=', $filter['label_id']]])->first();
        if (empty($info)) {
            return "该标签不存在!";
        }
        //查询该标签是否是自定义标签
        $label = (new AddressBookLabel())->where([['id', '=', $filter['label_id']]])->first();
        if (empty($label)) {
            return "该标签不存在!";
        }
        if ($label->is_default == 1 || $label->lab_type == 1) {
            return "疾病标签不能删除!";
        }
        $res = (new AddressBookRelateLabel())->where([['address_book_id', '=', $filter['address_book_id']], ['address_book_label_id', '=', $filter['label_id']]])->delete();
        if ($res) {
            return true;
        }
        return "删除失败";
    }


    /**
     * @param $filter
     * 通讯录添加label
     */
    public function delAddressBookLabel($filter)
    {
        $info = $this->where([['id', '=', $filter['id']]])->first();
        if (empty($info)) {
            return "该标签不存在!";
        }
        if ($info->is_default == 1) {
            return "该标签属于该工作室默认标签,不能删除!";
        }
        if ($info->lab_type != 2) {
            return "该标签属于疾病标签,不能删除!";
        }
        if ($info->work_id != $filter['work_id']) {
            return "该标签不属于该工作室,不能删除!";
        }
        $res = $this::destroy($filter['id']);
        if ($res) {
            (new AddressBookRelateLabel())->where([['address_book_label_id', '=', $filter['id']]])->delete();
            return true;
        }
        return "删除失败";
    }

    /**
     * @param $filter
     * @return mixed
     * 获取标签列表
     */
    public function getList($filter)
    {
        $info = $this->where([['work_id', '=', $filter['work_id']]])
            ->orderBy("is_default", "desc")
            ->orderBy("id", "asc")
            ->get();
        if (!empty($info)) {
            $res = $info = $info->toArray();
            $addressBookRelateLabel = new AddressBookRelateLabel();
            $list = [];
            foreach ($res as $k => &$v) {
                $v['numbers'] = $addressBookRelateLabel->where([['address_book_label_id', '=', $v['id']], ['work_id', '=', $filter['work_id']]])->count("id");
                if ($v['is_default'] == 1) {
                    $list['default'][] = $v;
                } else {
                    $list['no_default'][] = $v;
                }
            }
            return $list;
        }
        return [];
    }


    /**
     *批量打标签
     */
    public function giveLabelToUser($filter)
    {
        $goods_ids = Tool::handelString($filter['book_id']);
        if (empty($goods_ids)) {
            return "通讯录ID不能为空";
        }
        $goods_ids = array_unique($goods_ids);
        $data = [];
        $book = new AddressBook();
        $relate = new AddressBookRelateLabel();
        $label = (new AddressBookLabel())->where([['id', '=', $filter['label_id']]])->first();
        if (empty($label)) {
            return "该标签不存在,不能打标签!";
        }
        try {
            DB::beginTransaction();
            foreach ($goods_ids as $k => $v) {
                $booksInfo = $book->where([['id', '=', $v]])->first();
                if (empty($booksInfo)) {
                    continue;
                }
                if ($label->is_default == 1) {
                    //更换通讯录分组
                    if ($booksInfo->type != $label->num) { //如果类型不同
                        $book->where([['id', '=', $v]])->update(['type' => $label->num]);//修改通讯录
                        $lit = $relate->join('c_address_book_labels', 'c_address_book_labels.id', '=', 'c_address_book_relate_labels.address_book_label_id')
                            ->where([['c_address_book_relate_labels.address_book_id', '=', $v],
                                ['c_address_book_relate_labels.work_id', '=', $filter['work_id']],
                                ['c_address_book_labels.is_default', '=', 1],
                            ])
                            ->select(['c_address_book_relate_labels.id'])
                            ->pluck("c_address_book_relate_labels.id")->first();
                        $relate->where([['id','=',$lit]])->update(['address_book_label_id'=>$filter['label_id']]);
//                        $ww = [];
//                        if (!empty($lit)) {
//                            $ww[] = [function ($query) use ($lit) {
//                                $query->whereIn('id', $lit);
//                            }];
//                            $relate->where($ww)->delete();
//                        }
                    }
                }
                //如果是疾病标签,同步到到已关注的工作室中
                if ($label->lab_type == 1) {
                    $this->setOtherWorksLabel($label, $v, $filter);
                }
                $res = $relate::where([['address_book_id', '=', $v],
                    ['work_id', '=', $filter['work_id']],
                    ['address_book_label_id', '=', $filter['label_id']]])->first();
                if ($res) {
                    continue;
                }
                $data[$k]['address_book_id'] = $v;
                $data[$k]['work_id'] = $filter['work_id'];
                $data[$k]['address_book_label_id'] = $filter['label_id'];
                $data[$k]['created_at'] = date("Y-m-d H:i:s", time());
                $data[$k]['updated_at'] = date("Y-m-d H:i:s", time());
            }
            $yes = DB::table('c_address_book_relate_labels')->insert($data);
            if ($yes) {
                DB::commit();
                return true;
            }
        } catch (Exception $e) {
            DB::rollback(); // 回滚事务
        }
        return "添加失败";

    }

    /***
     * @param $label
     * @param $book_id
     * @param $filter
     * 疾病标签同步到其他工作室
     */
    public function setOtherWorksLabel($label, $book_id, $filter)
    {
        $address_book = (new AddressBook())->where([['id', '=', $book_id]])->first();
        if (!empty($address_book)) {
            $works = (new Follow())->where([['user_id', '=', $address_book->user_id], ['type', '=', 1], ['work_id', '<>', $filter['work_id']]])->get();
            foreach ($works as $k => $v) {
                $bk_id = (new AddressBook())->where([['work_id', '=', $v->id], ['phone', '=', $address_book->phone], ['user_name', '=', $address_book->user_name]])->first();
                if(empty($bk_id)){
                    continue;
                }
                //查询该工作室是否已存在该标签
                $exit = (new AddressBookLabel())->where([['work_id', '=', $v->id], ['label_name', '=', $label->label_name], ['lab_type', '=', 1]])->first();
                if (empty($exit)) {
                    //添加工作室标签填上
                    $lb = new AddressBookLabel();
                    $lb->label_name = $label->label_name;
                    $lb->work_id = $v->id;
                    $lb->lab_type = 1;
                    $lb->save();
                    $this->setRelateLabel($lb->id, $bk_id->id, $v->id);
                    continue;
                }
                $this->setRelateLabel($exit->id, $bk_id->id, $v->id);
            }
            return true;
        }
        return true;
    }

    //通步工作室标签
    public function setRelateLabel($label_id, $book_id, $work_id)
    {
        $relateLabel = new AddressBookRelateLabel();
        //判断该标签是否已经给改通讯录打上标签
        $val = (new AddressBookRelateLabel())->where([['address_book_id', '=', $book_id], ['work_id', '=', $work_id], ['address_book_label_id', '=', $label_id]])->first();
        if ($val) {
            return true;
        }
        $relateLabel->address_book_label_id = $label_id;
        $relateLabel->address_book_id = $book_id;
        $relateLabel->work_id = $work_id;
        return $relateLabel->save();
    }


}
